import paho.mqtt.client as mqtt
import datetime
import json
import time

host = '183.230.40.39'  # mqtt.heclouds.com
port = 6002

product_id = '497161'
device_id = '911825502'
auth_info = '1'

# 连接成功回调
def on_connect(client, userdata, flags, rc):
    print('Connected with result code ' + str(rc))
    # client.subscribe("$SYS/#")


# 消息接收回调
def on_message(client, userdata, msg):
    print(msg.topic, msg.payload)
    # client.publish(msg.topic, payload=msg.payload, qos=0)
# 建立连接
client = mqtt.Client(device_id)
client.username_pw_set(product_id, password=auth_info)
client.connect(host, port, 60)  # 心跳

# 指定回调函数
client.on_connect = on_connect
client.on_message = on_message



def get_temp():
    file = open("/sys/class/thermal/thermal_zone0/temp")
    temp = float(file.read()) / 1000
    file.close()
    print(temp)
    return temp

# 格式
def pubdata(data):
    j_d = json.dumps(data)
    j_l = len(j_d)
    arr = bytearray(j_l + 3)
    arr[0] = 1 # publish数据类型为json
    arr[1] = int(j_l / 256) # json数据长度 高位字节
    arr[2] = j_l % 256      # json数据长度 低位字节
    arr[3:] = j_d.encode('ascii') # json数据
    return arr

while 1:
    temperature = get_temp()  #获取CPU温度并上传
    CurTime = datetime.datetime.now()
    values = {
        'datastreams': [{
            'id': 'temp_cpu',
            'datapoints': [{
                'at': str(CurTime),  
                'value': temperature
            }]
        }]
    }
    client.publish('$dp', payload=pubdata(values), qos=0)
    time.sleep(3)

client.loop_forever()
